{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "# 策略绩效分析\n",
    "\n",
    "本notebook演示如何对交易策略进行全面的绩效分析，包括：\n",
    "- 收益率分析\n",
    "- 风险指标分析\n",
    "- 交易统计分析\n",
    "- 归因分析\n",
    "- 鲁棒性测试\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60746e11",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入必要的库\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from scipy import stats\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 设置中文字体和图表风格\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "sns.set_style('whitegrid')\n",
    "\n",
    "# 导入回测结果\n",
    "from pathlib import Path\n",
    "results_path = Path('../data/backtest_results.csv')\n",
    "\n",
    "if results_path.exists():\n",
    "    # 加载回测结果\n",
    "    results = pd.read_csv(results_path, parse_dates=['datetime'])\n",
    "    print(\"成功加载回测结果数据\")\n",
    "    print(f\"数据时间范围：{results['datetime'].min()} 至 {results['datetime'].max()}\")\n",
    "    print(f\"数据列：{', '.join(results.columns)}\")\n",
    "else:\n",
    "    print(\"示例：回测结果数据结构\")\n",
    "    results = pd.DataFrame({\n",
    "        'datetime': pd.date_range('2020-01-01', '2023-12-31', freq='D'),\n",
    "        'portfolio_value': np.random.uniform(1000000, 1500000, 1461),\n",
    "        'returns': np.random.normal(0.0002, 0.02, 1461),\n",
    "        'benchmark_returns': np.random.normal(0.0001, 0.015, 1461),\n",
    "        'positions': np.random.randint(1, 10, 1461),\n",
    "        'cash': np.random.uniform(100000, 200000, 1461),\n",
    "        'trades': np.random.randint(0, 5, 1461)\n",
    "    })\n",
    "    print(\"使用模拟数据进行演示\")\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## 1. 收益率分析\n",
    "\n",
    "分析策略的收益表现，包括：\n",
    "- 累计收益率\n",
    "- 年化收益率\n",
    "- 超额收益\n",
    "- 最大回撤\n",
    "- 收益风险比\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "092c9af1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def calculate_performance_metrics(returns, benchmark_returns=None):\n",
    "    \"\"\"计算策略绩效指标\n",
    "    \n",
    "    Args:\n",
    "        returns (pd.Series): 策略收益率序列\n",
    "        benchmark_returns (pd.Series, optional): 基准收益率序列\n",
    "        \n",
    "    Returns:\n",
    "        dict: 绩效指标字典\n",
    "    \"\"\"\n",
    "    # 计算累计收益\n",
    "    cum_returns = (1 + returns).cumprod() - 1\n",
    "    \n",
    "    # 计算年化收益率\n",
    "    years = len(returns) / 252  # 假设252个交易日\n",
    "    annual_return = (1 + cum_returns.iloc[-1]) ** (1/years) - 1\n",
    "    \n",
    "    # 计算波动率\n",
    "    annual_volatility = returns.std() * np.sqrt(252)\n",
    "    \n",
    "    # 计算夏普比率\n",
    "    risk_free_rate = 0.03  # 假设无风险利率为3%\n",
    "    excess_returns = returns - risk_free_rate/252\n",
    "    sharpe_ratio = np.sqrt(252) * excess_returns.mean() / returns.std()\n",
    "    \n",
    "    # 计算最大回撤\n",
    "    cum_returns_series = (1 + returns).cumprod()\n",
    "    rolling_max = cum_returns_series.expanding().max()\n",
    "    drawdowns = cum_returns_series/rolling_max - 1\n",
    "    max_drawdown = drawdowns.min()\n",
    "    \n",
    "    # 计算超额收益（如果有基准）\n",
    "    if benchmark_returns is not None:\n",
    "        cum_benchmark_returns = (1 + benchmark_returns).cumprod() - 1\n",
    "        excess_cum_returns = cum_returns - cum_benchmark_returns\n",
    "        tracking_error = (returns - benchmark_returns).std() * np.sqrt(252)\n",
    "        information_ratio = (returns - benchmark_returns).mean() / (returns - benchmark_returns).std() * np.sqrt(252)\n",
    "    else:\n",
    "        excess_cum_returns = None\n",
    "        tracking_error = None\n",
    "        information_ratio = None\n",
    "    \n",
    "    return {\n",
    "        'cumulative_return': cum_returns.iloc[-1],\n",
    "        'annual_return': annual_return,\n",
    "        'annual_volatility': annual_volatility,\n",
    "        'sharpe_ratio': sharpe_ratio,\n",
    "        'max_drawdown': max_drawdown,\n",
    "        'excess_return': excess_cum_returns.iloc[-1] if excess_cum_returns is not None else None,\n",
    "        'tracking_error': tracking_error,\n",
    "        'information_ratio': information_ratio\n",
    "    }\n",
    "\n",
    "# 计算绩效指标\n",
    "metrics = calculate_performance_metrics(results['returns'], results['benchmark_returns'])\n",
    "\n",
    "# 打印绩效指标\n",
    "print(\"策略绩效指标：\")\n",
    "print(f\"累计收益率: {metrics['cumulative_return']:.2%}\")\n",
    "print(f\"年化收益率: {metrics['annual_return']:.2%}\")\n",
    "print(f\"年化波动率: {metrics['annual_volatility']:.2%}\")\n",
    "print(f\"夏普比率: {metrics['sharpe_ratio']:.2f}\")\n",
    "print(f\"最大回撤: {metrics['max_drawdown']:.2%}\")\n",
    "print(f\"超额收益: {metrics['excess_return']:.2%}\")\n",
    "print(f\"跟踪误差: {metrics['tracking_error']:.2%}\")\n",
    "print(f\"信息比率: {metrics['information_ratio']:.2f}\")\n",
    "\n",
    "# 绘制收益曲线\n",
    "plt.figure(figsize=(12, 6))\n",
    "cum_returns = (1 + results['returns']).cumprod() - 1\n",
    "cum_benchmark_returns = (1 + results['benchmark_returns']).cumprod() - 1\n",
    "\n",
    "plt.plot(results['datetime'], cum_returns, label='策略收益')\n",
    "plt.plot(results['datetime'], cum_benchmark_returns, label='基准收益')\n",
    "plt.title('策略累计收益对比图')\n",
    "plt.xlabel('日期')\n",
    "plt.ylabel('累计收益率')\n",
    "plt.legend()\n",
    "plt.grid(True)\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## 2. 风险分析\n",
    "\n",
    "分析策略的风险特征，包括：\n",
    "- 收益分布分析\n",
    "- 波动率分析\n",
    "- 回撤分析\n",
    "- 风险价值(VaR)分析\n",
    "- 尾部风险分析\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "506c4596",
   "metadata": {},
   "outputs": [],
   "source": [
    "def analyze_risk(returns):\n",
    "    \"\"\"分析策略风险特征\n",
    "    \n",
    "    Args:\n",
    "        returns (pd.Series): 收益率序列\n",
    "    \"\"\"\n",
    "    # 1. 收益分布分析\n",
    "    plt.figure(figsize=(15, 10))\n",
    "    \n",
    "    # 1.1 直方图和核密度估计\n",
    "    plt.subplot(2, 2, 1)\n",
    "    sns.histplot(returns, kde=True, stat='density')\n",
    "    plt.title('收益率分布')\n",
    "    plt.xlabel('收益率')\n",
    "    plt.ylabel('密度')\n",
    "    \n",
    "    # 1.2 Q-Q图\n",
    "    plt.subplot(2, 2, 2)\n",
    "    stats.probplot(returns, dist=\"norm\", plot=plt)\n",
    "    plt.title('收益率Q-Q图')\n",
    "    \n",
    "    # 2. 波动率分析\n",
    "    # 计算20日滚动波动率\n",
    "    rolling_vol = returns.rolling(window=20).std() * np.sqrt(252)\n",
    "    plt.subplot(2, 2, 3)\n",
    "    plt.plot(rolling_vol.index, rolling_vol)\n",
    "    plt.title('20日滚动波动率')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('年化波动率')\n",
    "    \n",
    "    # 3. 回撤分析\n",
    "    cum_returns = (1 + returns).cumprod()\n",
    "    rolling_max = cum_returns.expanding().max()\n",
    "    drawdowns = cum_returns/rolling_max - 1\n",
    "    \n",
    "    plt.subplot(2, 2, 4)\n",
    "    plt.plot(drawdowns.index, drawdowns)\n",
    "    plt.title('回撤分析')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('回撤')\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    # 4. 风险统计指标\n",
    "    # 计算VaR和CVaR\n",
    "    var_95 = np.percentile(returns, 5)\n",
    "    cvar_95 = returns[returns <= var_95].mean()\n",
    "    \n",
    "    # 计算偏度和峰度\n",
    "    skewness = stats.skew(returns)\n",
    "    kurtosis = stats.kurtosis(returns)\n",
    "    \n",
    "    print(\"\\n风险统计指标：\")\n",
    "    print(f\"95% VaR: {var_95:.2%}\")\n",
    "    print(f\"95% CVaR: {cvar_95:.2%}\")\n",
    "    print(f\"偏度: {skewness:.2f}\")\n",
    "    print(f\"峰度: {kurtosis:.2f}\")\n",
    "    \n",
    "    # 5. 最大回撤期间分析\n",
    "    max_drawdown_idx = drawdowns.idxmin()\n",
    "    max_drawdown_start = drawdowns[:max_drawdown_idx][drawdowns[:max_drawdown_idx] == 0].index[-1]\n",
    "    max_drawdown_end = drawdowns[max_drawdown_idx:][drawdowns[max_drawdown_idx:] == 0].index[0] \\\n",
    "        if len(drawdowns[max_drawdown_idx:][drawdowns[max_drawdown_idx:] == 0]) > 0 \\\n",
    "        else drawdowns.index[-1]\n",
    "    \n",
    "    print(\"\\n最大回撤期间分析：\")\n",
    "    print(f\"开始日期: {max_drawdown_start}\")\n",
    "    print(f\"结束日期: {max_drawdown_end}\")\n",
    "    print(f\"持续天数: {(max_drawdown_end - max_drawdown_start).days}天\")\n",
    "    print(f\"最大回撤: {drawdowns.min():.2%}\")\n",
    "\n",
    "# 分析策略风险\n",
    "analyze_risk(results['returns'])\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## 3. 交易分析\n",
    "\n",
    "分析策略的交易特征，包括：\n",
    "- 交易频率统计\n",
    "- 持仓分析\n",
    "- 换手率分析\n",
    "- 交易成本分析\n",
    "- 盈亏比分析\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c849ed02",
   "metadata": {},
   "outputs": [],
   "source": [
    "def analyze_trading(results_df):\n",
    "    \"\"\"分析策略交易特征\n",
    "    \n",
    "    Args:\n",
    "        results_df (pd.DataFrame): 回测结果数据框\n",
    "    \"\"\"\n",
    "    # 1. 交易频率分析\n",
    "    daily_trades = results_df['trades']\n",
    "    \n",
    "    plt.figure(figsize=(15, 10))\n",
    "    \n",
    "    # 1.1 每日交易次数分布\n",
    "    plt.subplot(2, 2, 1)\n",
    "    sns.histplot(daily_trades[daily_trades > 0], bins=20)\n",
    "    plt.title('每日交易次数分布')\n",
    "    plt.xlabel('交易次数')\n",
    "    plt.ylabel('频率')\n",
    "    \n",
    "    # 1.2 交易次数的时间序列\n",
    "    plt.subplot(2, 2, 2)\n",
    "    plt.plot(results_df['datetime'], daily_trades)\n",
    "    plt.title('每日交易次数时间序列')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('交易次数')\n",
    "    \n",
    "    # 2. 持仓分析\n",
    "    # 2.1 持仓数量时间序列\n",
    "    plt.subplot(2, 2, 3)\n",
    "    plt.plot(results_df['datetime'], results_df['positions'])\n",
    "    plt.title('持仓数量时间序列')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('持仓数量')\n",
    "    \n",
    "    # 2.2 现金比例时间序列\n",
    "    cash_ratio = results_df['cash'] / results_df['portfolio_value']\n",
    "    plt.subplot(2, 2, 4)\n",
    "    plt.plot(results_df['datetime'], cash_ratio)\n",
    "    plt.title('现金比例时间序列')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('现金比例')\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    # 3. 交易统计\n",
    "    total_days = len(results_df)\n",
    "    trading_days = len(results_df[results_df['trades'] > 0])\n",
    "    avg_positions = results_df['positions'].mean()\n",
    "    avg_cash_ratio = cash_ratio.mean()\n",
    "    \n",
    "    print(\"\\n交易统计：\")\n",
    "    print(f\"总交易日数: {total_days}天\")\n",
    "    print(f\"有交易的天数: {trading_days}天\")\n",
    "    print(f\"交易频率: {trading_days/total_days:.2%}\")\n",
    "    print(f\"平均每日交易次数: {daily_trades.mean():.2f}\")\n",
    "    print(f\"平均持仓数量: {avg_positions:.2f}\")\n",
    "    print(f\"平均现金比例: {avg_cash_ratio:.2%}\")\n",
    "    \n",
    "    # 4. 持仓周转率（以持仓变化作为简化估计）\n",
    "    position_changes = abs(results_df['positions'].diff())\n",
    "    turnover_ratio = position_changes.sum() / (2 * total_days * avg_positions) if avg_positions > 0 else 0\n",
    "    \n",
    "    print(\"\\n周转率分析：\")\n",
    "    print(f\"年化换手率: {turnover_ratio * 252:.2%}\")\n",
    "\n",
    "# 分析交易特征\n",
    "analyze_trading(results)\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## 4. 归因分析\n",
    "\n",
    "分析策略收益的来源，包括：\n",
    "- 市场暴露分析\n",
    "- 风格因子暴露\n",
    "- 行业暴露分析\n",
    "- Alpha分解\n",
    "- 业绩归因\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67f2102e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def perform_attribution_analysis(returns, benchmark_returns):\n",
    "    \"\"\"进行归因分析\n",
    "    \n",
    "    Args:\n",
    "        returns (pd.Series): 策略收益率序列\n",
    "        benchmark_returns (pd.Series): 基准收益率序列\n",
    "    \"\"\"\n",
    "    # 1. 计算滚动beta\n",
    "    def calculate_rolling_beta(returns, benchmark_returns, window=60):\n",
    "        # 计算协方差矩阵\n",
    "        covariance = returns.rolling(window=window).cov(benchmark_returns)\n",
    "        # 计算基准收益率的方差\n",
    "        benchmark_variance = benchmark_returns.rolling(window=window).var()\n",
    "        # 计算beta\n",
    "        return covariance / benchmark_variance\n",
    "    \n",
    "    rolling_beta = calculate_rolling_beta(returns, benchmark_returns)\n",
    "    \n",
    "    # 2. 计算超额收益分解\n",
    "    # 假设使用单因子模型：R = α + β*Rm + ε\n",
    "    # 使用全样本beta进行分解\n",
    "    X = sm.add_constant(benchmark_returns)\n",
    "    model = sm.OLS(returns, X)\n",
    "    results = model.fit()\n",
    "    \n",
    "    alpha = results.params[0]\n",
    "    beta = results.params[1]\n",
    "    r_squared = results.rsquared\n",
    "    \n",
    "    # 3. 绘制分析图\n",
    "    plt.figure(figsize=(15, 10))\n",
    "    \n",
    "    # 3.1 滚动beta\n",
    "    plt.subplot(2, 2, 1)\n",
    "    plt.plot(rolling_beta.index, rolling_beta)\n",
    "    plt.title('60日滚动Beta')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('Beta')\n",
    "    \n",
    "    # 3.2 残差收益率\n",
    "    residuals = results.resid\n",
    "    plt.subplot(2, 2, 2)\n",
    "    plt.plot(residuals.index, residuals.cumsum())\n",
    "    plt.title('累计残差收益（Alpha）')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('累计残差收益')\n",
    "    \n",
    "    # 3.3 收益分解\n",
    "    market_contribution = beta * benchmark_returns\n",
    "    alpha_contribution = returns - market_contribution\n",
    "    \n",
    "    plt.subplot(2, 2, 3)\n",
    "    plt.plot(returns.index, alpha_contribution.cumsum(), label='Alpha贡献')\n",
    "    plt.plot(returns.index, market_contribution.cumsum(), label='市场贡献')\n",
    "    plt.title('收益分解')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('累计贡献')\n",
    "    plt.legend()\n",
    "    \n",
    "    # 3.4 QQ图分析残差\n",
    "    plt.subplot(2, 2, 4)\n",
    "    stats.probplot(residuals, dist=\"norm\", plot=plt)\n",
    "    plt.title('残差Q-Q图')\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    # 4. 打印归因分析结果\n",
    "    print(\"\\n归因分析结果：\")\n",
    "    print(f\"Alpha（年化）: {alpha * 252:.2%}\")\n",
    "    print(f\"Beta: {beta:.2f}\")\n",
    "    print(f\"R方: {r_squared:.2%}\")\n",
    "    \n",
    "    # 5. 计算业绩分解\n",
    "    total_return = (1 + returns).prod() - 1\n",
    "    market_return = (1 + market_contribution).prod() - 1\n",
    "    alpha_return = (1 + alpha_contribution).prod() - 1\n",
    "    \n",
    "    print(\"\\n收益分解：\")\n",
    "    print(f\"总收益: {total_return:.2%}\")\n",
    "    print(f\"市场贡献: {market_return:.2%}\")\n",
    "    print(f\"Alpha贡献: {alpha_return:.2%}\")\n",
    "    \n",
    "    # 6. 计算信息比率\n",
    "    tracking_error = residuals.std() * np.sqrt(252)\n",
    "    information_ratio = (alpha * 252) / tracking_error\n",
    "    \n",
    "    print(\"\\n风险调整指标：\")\n",
    "    print(f\"跟踪误差: {tracking_error:.2%}\")\n",
    "    print(f\"信息比率: {information_ratio:.2f}\")\n",
    "\n",
    "# 进行归因分析\n",
    "try:\n",
    "    import statsmodels.api as sm\n",
    "    perform_attribution_analysis(results['returns'], results['benchmark_returns'])\n",
    "except ImportError:\n",
    "    print(\"注意：需要安装statsmodels包来进行完整的归因分析。\")\n",
    "    print(\"可以使用命令：pip install statsmodels\")\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## 5. 鲁棒性测试\n",
    "\n",
    "通过以下方面验证策略的稳定性：\n",
    "- 参数敏感性分析\n",
    "- 样本外测试\n",
    "- 不同市场环境测试\n",
    "- 交易成本敏感性\n",
    "- 流动性约束测试\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dab5b2c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def perform_robustness_tests(returns, benchmark_returns):\n",
    "    \"\"\"进行策略鲁棒性测试\n",
    "    \n",
    "    Args:\n",
    "        returns (pd.Series): 策略收益率序列\n",
    "        benchmark_returns (pd.Series): 基准收益率序列\n",
    "    \"\"\"\n",
    "    # 1. 分析不同市场环境下的表现\n",
    "    # 根据基准收益率划分市场环境\n",
    "    market_conditions = pd.qcut(benchmark_returns, \n",
    "                              q=3, \n",
    "                              labels=['熊市', '震荡市', '牛市'])\n",
    "    \n",
    "    # 计算不同市场环境下的表现\n",
    "    performance_by_market = pd.DataFrame({\n",
    "        '策略收益率': returns,\n",
    "        '基准收益率': benchmark_returns,\n",
    "        '市场环境': market_conditions\n",
    "    }).groupby('市场环境').agg({\n",
    "        '策略收益率': ['mean', 'std'],\n",
    "        '基准收益率': ['mean', 'std']\n",
    "    })\n",
    "    \n",
    "    # 2. 交易成本敏感性分析\n",
    "    cost_levels = [0, 0.001, 0.002, 0.003, 0.004, 0.005]  # 0到50bp的交易成本\n",
    "    cost_impact = []\n",
    "    \n",
    "    for cost in cost_levels:\n",
    "        # 假设每次换仓都产生成本\n",
    "        turnover_cost = abs(returns).mean() * cost\n",
    "        net_return = returns - turnover_cost\n",
    "        \n",
    "        # 计算年化收益和夏普比率\n",
    "        annual_return = (1 + net_return).prod() ** (252/len(net_return)) - 1\n",
    "        sharpe = np.sqrt(252) * net_return.mean() / net_return.std()\n",
    "        \n",
    "        cost_impact.append({\n",
    "            '交易成本(bp)': cost * 10000,\n",
    "            '年化收益率': annual_return,\n",
    "            '夏普比率': sharpe\n",
    "        })\n",
    "    \n",
    "    cost_impact_df = pd.DataFrame(cost_impact)\n",
    "    \n",
    "    # 3. 绘制分析图\n",
    "    plt.figure(figsize=(15, 10))\n",
    "    \n",
    "    # 3.1 不同市场环境下的表现对比\n",
    "    plt.subplot(2, 2, 1)\n",
    "    performance_by_market['策略收益率']['mean'].plot(kind='bar', yerr=performance_by_market['策略收益率']['std'])\n",
    "    plt.title('不同市场环境下的策略表现')\n",
    "    plt.xlabel('市场环境')\n",
    "    plt.ylabel('日均收益率')\n",
    "    \n",
    "    # 3.2 交易成本敏感性分析\n",
    "    plt.subplot(2, 2, 2)\n",
    "    plt.plot(cost_impact_df['交易成本(bp)'], cost_impact_df['年化收益率'])\n",
    "    plt.title('交易成本敏感性分析')\n",
    "    plt.xlabel('交易成本(bp)')\n",
    "    plt.ylabel('年化收益率')\n",
    "    \n",
    "    # 3.3 滚动窗口分析\n",
    "    window_size = 60  # 60天窗口\n",
    "    rolling_sharpe = np.sqrt(252) * returns.rolling(window=window_size).mean() / returns.rolling(window=window_size).std()\n",
    "    \n",
    "    plt.subplot(2, 2, 3)\n",
    "    plt.plot(rolling_sharpe.index, rolling_sharpe)\n",
    "    plt.title('60日滚动夏普比率')\n",
    "    plt.xlabel('日期')\n",
    "    plt.ylabel('夏普比率')\n",
    "    \n",
    "    # 3.4 子样本分析\n",
    "    mid_point = len(returns) // 2\n",
    "    periods = ['前半样本', '后半样本']\n",
    "    sub_sample_returns = [returns[:mid_point], returns[mid_point:]]\n",
    "    sub_sample_stats = []\n",
    "    \n",
    "    for period, ret in zip(periods, sub_sample_returns):\n",
    "        annual_return = (1 + ret).prod() ** (252/len(ret)) - 1\n",
    "        sharpe = np.sqrt(252) * ret.mean() / ret.std()\n",
    "        max_drawdown = (ret.cumsum() - ret.cumsum().expanding().max()).min()\n",
    "        \n",
    "        sub_sample_stats.append({\n",
    "            '样本期': period,\n",
    "            '年化收益率': annual_return,\n",
    "            '夏普比率': sharpe,\n",
    "            '最大回撤': max_drawdown\n",
    "        })\n",
    "    \n",
    "    sub_sample_df = pd.DataFrame(sub_sample_stats)\n",
    "    \n",
    "    plt.subplot(2, 2, 4)\n",
    "    sub_sample_df.set_index('样本期')[['年化收益率', '夏普比率', '最大回撤']].plot(kind='bar')\n",
    "    plt.title('子样本分析')\n",
    "    plt.xlabel('样本期')\n",
    "    plt.ylabel('指标值')\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    # 4. 打印详细分析结果\n",
    "    print(\"\\n不同市场环境下的表现：\")\n",
    "    print(performance_by_market)\n",
    "    \n",
    "    print(\"\\n交易成本敏感性分析：\")\n",
    "    print(cost_impact_df)\n",
    "    \n",
    "    print(\"\\n子样本分析：\")\n",
    "    print(sub_sample_df)\n",
    "\n",
    "# 进行鲁棒性测试\n",
    "perform_robustness_tests(results['returns'], results['benchmark_returns'])\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## 6. 总结与建议\n",
    "\n",
    "基于以上分析，我们可以得出以下结论：\n",
    "\n",
    "### 策略优势\n",
    "1. **收益能力**\n",
    "   - 分析策略的绝对收益和相对收益\n",
    "   - 评估风险调整后的收益指标\n",
    "\n",
    "2. **风险控制**\n",
    "   - 评估波动率和回撤控制能力\n",
    "   - 分析风险暴露的合理性\n",
    "\n",
    "3. **稳定性**\n",
    "   - 评估不同市场环境下的表现\n",
    "   - 分析交易成本的影响\n",
    "\n",
    "### 存在的问题\n",
    "1. **需要优化的方面**\n",
    "   - 列出需要改进的具体指标\n",
    "   - 提供优化的方向建议\n",
    "\n",
    "2. **潜在风险**\n",
    "   - 识别策略的脆弱点\n",
    "   - 提供风险控制建议\n",
    "\n",
    "### 下一步计划\n",
    "1. **策略优化**\n",
    "   - 参数优化建议\n",
    "   - 风险控制改进方案\n",
    "\n",
    "2. **实盘部署**\n",
    "   - 实盘环境的特殊考虑\n",
    "   - 监控和调整计划\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
